package org.jeecg.modules.wei.job;

import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.HttpRequest;
import org.jeecg.modules.webcrawler.util.WebCrawlerCacheUtils;
import org.jeecg.modules.webcrawler.util.bloomfilter.BloomFilterHelper;
import org.jeecg.modules.webcrawler.util.bloomfilter.BloomRedisService;
import org.jeecg.modules.wei.entity.WeiArticle;
import org.jeecg.modules.wei.entity.WeiComment;
import org.jeecg.modules.wei.entity.WeiCountData;
import org.jeecg.modules.wei.service.IWeiArticleService;
import org.jeecg.modules.wei.service.IWeiCommentService;
import org.jeecg.modules.wei.service.IWeiCountDataService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Maps;

import lombok.extern.slf4j.Slf4j;

/**
 * 微信   文章列表、评论列表
 * @author Scott
 */
@Slf4j
public class WeixinJob implements Job {
	
	@Autowired
	private IWeiArticleService weiArticleService;
	
	@Autowired
	private IWeiCommentService weiCommentService;
	
	@Autowired
	private IWeiCountDataService weiCountDataService;
	
	@Autowired
    private BloomRedisService redisService;

    @Autowired
    private BloomFilterHelper bloomFilterHelper;
	/**
	 * 若参数变量名修改 QuartzJobController中也需对应修改
	 */
	private String parameter;

	public void setParameter(String parameter) {
		this.parameter = parameter;
	}
	
	@Override
	public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
		log.info(String.format(" 微信 定时器 !  时间:" + DateUtils.getTimestamp()));
		int days = Integer.parseInt(parameter);
		WeixinJob wx = new WeixinJob();
		Map<String, String> weibo = Maps.newConcurrentMap();
		weibo.put("12", "平安邯郸");
//		weibo.put("13", "邯郸公安");
//		weibo.put("14", "复兴公安");
//		weibo.put("15", "大名公安");
//		weibo.put("16", "平安丛台");
//		weibo.put("17", "平安永年");
//		weibo.put("18", "涉县公安局");
//		weibo.put("19", "馆陶公安");
//		weibo.put("20", "邯山区公安分局");
		
		System.out.println("-------[Iterator循环遍历]通过EntrySet取出map数据---------");		
		Iterator<Entry<String, String>> iterator = weibo.entrySet().iterator();  //map.entrySet()得到的是set集合，可以使用迭代器遍历
		while(iterator.hasNext()){
			Entry<String, String> entry = iterator.next();
			String uid = entry.getKey();
			String createby = entry.getValue();
			System.out.println("key值："+entry.getKey()+" value值："+entry.getValue());
			String accessToken = get_token(uid);
			getusersummary(accessToken, uid, createby);
			System.out.println(accessToken);
			
			for (int i = days; i > 0; i--) {
				String day = DateUtils.getYesterday("yyyy-MM-dd", -1*i);
				System.out.println(day);
				JSONArray articlelist = getarticletotal(accessToken, day);
				
				for (int j = 0; j < articlelist.size(); j++) {
					JSONObject  article = articlelist.getJSONObject(j);
					String url = article.getString("url");
					Date createTime = DateUtils.stringToDate(article.getString("ref_date"),"yyyy-MM-dd");
					if(article.getString("title").contains("局长")) {
						if(redisService.includeByBloomFilter(bloomFilterHelper, "gonganjuzhang"+10, url)){  //url已存在
							
						}else {
							redisService.addByBloomFilter(bloomFilterHelper, "gonganjuzhang"+10, url);
							if(WebCrawlerCacheUtils.getTotalCount(url, 10) > 0) {
								break;
							}else {
								WebCrawlerCacheUtils.addArticle(article.getString("title"), url, createTime, 10, "邯郸新闻网");
							}
						}
					}
					
					
					
					
					System.out.println(article.getString("title"));
					//System.out.println("分享次数"+article.getString("share_count"));
					System.out.println(article.getString("msgid"));
					System.out.println(article.getString("ref_date"));
					System.out.println(article.getString("url"));
					JSONArray details = article.getJSONArray("details");
					JSONObject detail = details.getJSONObject(details.size() - 1);
					System.out.println("分享次数："+detail.getInteger("share_count"));
					System.out.println("浏览量："+detail.getInteger("int_page_read_count"));
					WeiArticle info = new WeiArticle();
					info.setTitle(article.getString("title"));
					info.setId(article.getString("msgid"));
					info.setMsgid(info.getId());
					info.setUrl(article.getString("url"));
					info.setShareCount(detail.getInteger("share_count"));
					info.setClickCount(detail.getInteger("int_page_read_count"));
					
					int commentcount = weiCommentService.queryListCount(info.getId());
					info.setCommentCount(commentcount);
					info.setType(1);
					info.setUid(uid);
					info.setCreateBy(createby);
					
					info.setCreateTime(createTime);
					try {
						weiArticleService.saveOrUpdate(info);
					} catch (Exception e) {
						e.printStackTrace();
					}
					System.out.println("-----------------------------------------------------------");
					
					//getcommentlist(accessToken, info.getMsgid());
					
				}
			}
			
		}
		
		
		
		
		
		
	}
	
	
	
	public static String get_token(String uid) {
		String token = HttpRequest.sendGet("http://gongan.hbweiyinqing.cn/f/mp/api/getAccessToken", "appid=wx15f4f748100f9b2f");
		System.out.println("获取token"+token);

		return token;
	}
	
	
	
	public static JSONArray getarticletotal(String accessToken, String day) {
		JSONObject param = new JSONObject();
		param.put("begin_date", day);
		param.put("end_date", day);
	
		String result = HttpRequest.httpPostWithJSON("https://api.weixin.qq.com/datacube/getarticletotal?access_token="+accessToken, param);
		System.out.println("图文分析数据接口");
		System.out.println(result);
		JSONObject json = JSONObject.parseObject(result);
		if(json.containsKey("list")) {
			return json.getJSONArray("list");
		}else {
			return null;
		}
	}
	public  JSONObject userinfo(String accessToken,String openid) {

		
		String result = HttpRequest.sendGet("https://api.weixin.qq.com/cgi-bin/user/info", "access_token="+accessToken+"&openid="+openid+"&lang=zh_CN");
		System.out.println("获取用户信息");
		return JSONObject.parseObject(result);
	}
	
	public  void getusersummary(String accessToken,String uid,String createby) {
		JSONObject param = new JSONObject();
		param.put("count", "1");
	
		String result = HttpRequest.httpPostWithJSON("https://api.weixin.qq.com/cgi-bin/user/get?access_token="+accessToken, param);
		System.out.println(result);
		System.out.println("获取用户信息");
		JSONObject total =  JSONObject.parseObject(result);
		try {
			String today = DateUtils.date2Str(DateUtils.date_sdf);
			WeiCountData info = 	weiCountDataService.getOne(new QueryWrapper<WeiCountData>()
					.eq("uid", uid)
					.eq("time", today));
			if(info == null) {
				info = new WeiCountData();
			}
			info.setUid(uid);
			info.setType(1);
			info.setTime(today);
			info.setCreateBy(createby);
			info.setCreateTime(new Date());
			info.setTotal(total.getInteger("total"));
			weiCountDataService.saveOrUpdate(info);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	
	public static void main(String[] args) {
		WeixinJob wx = new WeixinJob();
		Map<String, String> weibo = Maps.newConcurrentMap();
		weibo.put("12", "平安邯郸");
//		weibo.put("13", "邯郸公安");
//		weibo.put("14", "复兴公安");
//		weibo.put("15", "大名公安");
//		weibo.put("16", "平安丛台");
//		weibo.put("17", "平安永年");
//		weibo.put("18", "涉县公安局");
//		weibo.put("19", "馆陶公安");
//		weibo.put("20", "邯山区公安分局");
		
		System.out.println("-------[Iterator循环遍历]通过EntrySet取出map数据---------");		
		Iterator<Entry<String, String>> iterator = weibo.entrySet().iterator();  //map.entrySet()得到的是set集合，可以使用迭代器遍历
		while(iterator.hasNext()){
			Entry<String, String> entry = iterator.next();
			String uid = entry.getKey();
			String createby = entry.getValue();
			System.out.println("key值："+entry.getKey()+" value值："+entry.getValue());
			String accessToken = get_token(uid);
			System.out.println(accessToken);
			//getusersummary(accessToken);
			JSONArray articlelist = getarticletotal(accessToken, "2020-09-21");
			for (int j = 0; j < articlelist.size(); j++) {
				JSONObject  article = articlelist.getJSONObject(j);
				System.out.println(article.getString("title"));
				//System.out.println("分享次数"+article.getString("share_count"));
				System.out.println(article.getString("msgid"));
				System.out.println(article.getString("ref_date"));
				System.out.println(article.getString("url"));
				JSONArray details = article.getJSONArray("details");
				JSONObject detail = details.getJSONObject(details.size() - 1);
				System.out.println("分享次数："+detail.getInteger("share_count"));
				System.out.println("浏览量："+detail.getInteger("int_page_read_count"));
//				WeiArticle info = new WeiArticle();
				System.out.println(article.getString("title"));
//				info.setTitle(article.getString("title"));
//				info.setId(article.getString("msgid"));
//				info.setMsgid(info.getId());
//				info.setUrl(article.getString("url"));
//				info.setType(1);
//				Date createTime = DateUtils.stringToDate(article.getString("ref_date"),"yyyy-MM-dd");
//				info.setCreateTime(createTime);
//				weiArticleService.saveOrUpdate(info);
				System.out.println("-----------------------------------------------------------");
				
				//getcommentlist(accessToken, info.getMsgid());
				
			}
			
		}

//		int days = 2;
//	
//		for (int i = days; i > 0; i--) {
//			String day = DateUtils.getYesterday("yyyy-MM-dd", -1*i);
//			System.out.println(day);
//			JSONArray articlelist = wx.getarticletotal(accessToken, day);
//			for (int j = 0; j < articlelist.size(); j++) {
//				JSONObject  article = articlelist.getJSONObject(j);
//				System.out.println(article.getString("title"));
//				System.out.println(article.getString("msgid"));
//				System.out.println(article.getString("ref_date"));
//				WeiArticle info = new WeiArticle();
//				info.setTitle(article.getString("title"));
//				info.setId(article.getString("msgid"));
//				info.setMsgid(info.getId());
//				info.setUrl(article.getString("url"));
//				info.setType(1);
//				Date createTime = DateUtils.stringToDate(article.getString("ref_date"),"yyyy-MM-dd");
//				info.setCreateTime(createTime);
//				System.out.println("-----------------------------------------------------------");
//				
//				//getcommentlist(accessToken, info.getMsgid());
//				
//			}
//		}
//		
//		

	}
	
}
